from apps.common.base.views import *
from apps.common.script.service import *
from apps.pay.financeForLessee.service import startFinanceHistory, startFinance
from apps.system.lessee.dao import LesseeDao
from apps.common.third.createImgCode import generate_captcha
from rest_framework import viewsets, status
from apps.pay.recordIncomes.functions import autoFreeBalanceLockedRecord
from apps.pay.order.payReturnHandle.dismantleOrderByItem import dismantleOrderByItemHandle
from apps.pay.order.sceneHandle import payReturnScene
import tempfile
from apps.system.bank.dao import BankDao
from apps.pay.financeForLessee.service import financeFun
from apps.pay.recordIncomes.shopSettle import shopSettleFun
from apps.common.script.checkData import CheckData
from apps.common.script.pay_system import PaySystem

class ScriptViewSet(BaseViewSet):
    authentication_classes = []
    permission_classes = []
    @action(methods=['post'], detail=False)
    def handle(self, request):
        params = getRequestParams(request)
        # try:
        #     handleSku()
        # except ValidationError as e:
        #     print('e', e)
        #     return Response(response_message(str(e)))
        
        # startFinanceHistory()
        # handleItem5()
        # generate_captcha()
        # handleItem4()
        # handleItem6()
        # for order in OrderDao().findAllSubOrder():
        #     if not order.expressageinfo:
        #         order.expressageinfo = order.order.expressageinfo
        #         order.save()
        # dismantleOrderByItemHandle(OrderDao().findOneByOrderId('202504160920372235'))
        # payReturnScene('incomes', '202504260146200639', '')
        # autoFreeBalanceLockedRecord()
        # function6('中通', '中通快递', 'zhongtong')
        # function6('圆通', '圆通速递', 'yuantong')
        # function6('申通', '申通快递', 'shentong')
        # function6('邮政', '邮政电商标快', 'youzhengdsbk')
        # function6('顺丰', '顺丰快运', 'shunfengkuaiyun')
        # function6('极兔', '极兔速递', 'jtexpress')
        # function6('京东', '京东物流', 'jd')
        # function6('韵达', '韵达快递', 'yunda')
        # function7()
        # payReturnScene('wxpay', '2025051422115410737020', '', 'lzpay', '')
        # function3()
        PaySystem().principalDouble()
        return Response(response_message('执行成功'))
    
    # 数据巡视
    @action(methods=['post'], detail=False)
    def checkData(self, request):
        params = getRequestParams(request)
        CheckData().handle()
        return Response(response_message('巡检完成'))
    
    @action(methods=['post'], detail=False)
    def handle2(self, request):

        fp = request.FILES.get('file')
        if not fp:
            return Response(response_action('10002', '文件上传为空'))
        # 保存文件到临时文件
        with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(fp.name)[1]) as temp_file:
            for chunk in fp.chunks():
                temp_file.write(chunk)
            temp_file_path = temp_file.name
        
        try:
            # 打开Excel文件
            workbook = xlrd.open_workbook(temp_file_path)
            # 获取第一个工作表
            worksheet = workbook.sheet_by_index(0)
            
            _errors = ''
            # 获取表头
            titles = ['name', 'code']
            headers = []
            for col in range(0, len(titles)):
                value = worksheet.cell_value(0, col)
                if titles[col] != value:
                    _errors = _errors + '第1行' + titles[col] + '与导入模版表头不匹配，请下载最新导入模版；'
                else:
                    headers.append(value)
            if len(_errors) > 0:
                return Response(response_action(10002, _errors))
            # 存储所有行数据----------------------------
            data = []
            # 遍历每一行
            for row in range(1, worksheet.nrows):
                row_data = {}
                for col in range(0, len(headers)):
                    if not worksheet.cell_value(row, col) and col!=0:
                        _errors = _errors + '第' + str(row) + '行' + headers[col] + '数据不存在；'
                    row_data[headers[col]] = worksheet.cell_value(row, col)
                row_data['rowIndex'] = row + 1
                data.append(row_data)
                BankDao().create(row_data)
            print('data', data)
            return Response(response_message(data))
        except Exception as e:
            print(e)
            return Response(response_action(10002, '导入模版格式错误，请下载最新导入模版'))
        
    @action(methods=['get'], detail=False,)
    def handleTimer(self, request):
        params = getRequestParams(request)
        date = datetime.datetime.now().strftime('%Y-%m-%d')
        autoFreeBalanceLockedRecord(date)
        if params.get('date') == 'today':
            shopSettleFun(datetime.datetime.now())
            financeFun('day', datetime.datetime.now())
        else:
            shopSettleFun(datetime.datetime.now()-datetime.timedelta(days=1))
            financeFun('day', datetime.datetime.now()-datetime.timedelta(days=1))
        return Response(response_message('执行成功'))
    
    @action(methods=['get'], detail=False,)
    def handle3(self, request):

        return Response(response_message('测试'))